function [ber_rayleigh, fig_handle] = rayleigh_detection(EbN0_dB, num_bits)
% 瑞利衰落信道中信号检测性能分析
% 输入:
%   EbN0_dB - 比特信噪比范围 (dB)
%   num_bits - 仿真比特数
% 输出:
%   ber_rayleigh - 误比特率
%   fig_handle - 图形句柄

    EbN0_linear = 10.^(EbN0_dB/10);
    ber_rayleigh = zeros(1, length(EbN0_dB));
    
    % 添加路径
    addpath('../Common');
    colors = color_definitions();
    
    fprintf('=== 瑞利衰落信道中信号检测性能分析 ===\n');
    
    for eb_idx = 1:length(EbN0_dB)
        fprintf('仿真 Eb/N0 = %d dB...\n', EbN0_dB(eb_idx));
        
        % 生成随机比特
        tx_bits = randi([0, 1], num_bits, 1);
        
        % BPSK调制
        tx_symbols = 2 * tx_bits - 1;
        
        % 瑞利衰落信道
        rayleigh_fading = sqrt(0.5) * (randn(num_bits, 1) + 1i * randn(num_bits, 1));
        
        % 添加AWGN噪声
        noise_power = 1 / (2 * EbN0_linear(eb_idx));
        noise = sqrt(noise_power) * (randn(num_bits, 1) + 1i * randn(num_bits, 1));
        
        % 接收信号
        rx_symbols = tx_symbols .* rayleigh_fading + noise;
        
        % 理想信道估计 (假设已知信道状态)
        estimated_symbols = rx_symbols ./ rayleigh_fading;
        
        % 判决
        rx_bits = (real(estimated_symbols) > 0);
        
        % 计算误比特率
        ber_rayleigh(eb_idx) = sum(tx_bits ~= rx_bits) / num_bits;
        
        fprintf('BER = %.4e\n', ber_rayleigh(eb_idx));
    end
    
    % 理论BER曲线
    theory_ber = 0.5 * (1 - sqrt(EbN0_linear ./ (1 + EbN0_linear)));
    
    % 绘制结果
    fig_handle = figure('Name', '瑞利衰落信道检测性能', 'Position', [100, 100, 1000, 600]);
    
    subplot(1,2,1);
    semilogy(EbN0_dB, ber_rayleigh, 'o-', 'LineWidth', 2, 'Color', colors(1,:));
    hold on;
    semilogy(EbN0_dB, theory_ber, 'k--', 'LineWidth', 2);
    grid on;
    xlabel('Eb/N0 (dB)');
    ylabel('误比特率 (BER)');
    title('瑞利衰落信道BPSK性能');
    legend('仿真结果', '理论曲线', 'Location', 'SouthWest');
    
    % 信道幅度分布
    subplot(1,2,2);
    num_samples = 10000;
    rayleigh_samples = sqrt(0.5) * (randn(num_samples, 1) + 1i * randn(num_samples, 1));
    histogram(abs(rayleigh_samples), 50, 'Normalization', 'pdf');
    hold on;
    
    % 理论瑞利分布
    x_theory = 0:0.01:4;
    rayleigh_pdf = x_theory .* exp(-x_theory.^2 / 2);
    plot(x_theory, rayleigh_pdf, 'r-', 'LineWidth', 2);
    
    grid on;
    xlabel('信道幅度');
    ylabel('概率密度');
    title('瑞利衰落分布');
    legend('仿真直方图', '理论分布');
    
    % 保存图片
    saveas(fig_handle, 'results/rayleigh_detection_analysis.png');
end